﻿using Plugin.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;

namespace Plugin.Host
{
    class PluginLoadContext:AssemblyLoadContext
    {
        AssemblyDependencyResolver _resolver;
        public PluginLoadContext(string pluginPath,bool collectible):base(name:Path.GetFileName(pluginPath),collectible)
        {
            // Create a resolver to help us find dependencies.
            _resolver = new AssemblyDependencyResolver(pluginPath);
        }
        protected override Assembly? Load(AssemblyName assemblyName)
        {
            // 如果是 Plugin.Common.dll 就返回null 让 BCL 去加载它 还可以返回
            if(assemblyName.Name == typeof(ITextPlugin).Assembly.GetName().Name)
            {
                //return typeof(ITextPlugin).Assembly;
                return null;
            }
            string target = _resolver.ResolveAssemblyToPath(assemblyName)!;

            if (target != null)
                return LoadFromAssemblyPath(target);

            // Could be BCL assembly. Allow the default context to resolve.
            return null;
        }

        protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
        {
            string path = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName)!;
            return path == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(path);
        }



    }
}
